package com.xcoder.thread;

/**
 * 请编写一个多线程程序，其中一个线程完成对某个对象的int成员变量的增加操作，
 * 即每次加1，另一个线程完成对该对象的成员变量的减操作，即每次减1;
 * 同时要保证该变量的值不会小于0，不会大于1，该变量的初始值为0
 */
public class Q1 {

    public static void main(String[] args) {
        Operation op = new Operation();
        new AddThread(op).start();
        new SubThread(op).start();
    }

    private static class AddThread extends Thread {

        private Operation op;

        public AddThread(Operation op) {
            this.op = op;
        }

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 20; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.op.add();
            }
        }
    }

    private static class SubThread extends Thread {

        private Operation op;

        public SubThread(Operation op) {
            this.op = op;
        }

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 20; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.op.sub();
            }
        }
    }
}

class Operation {

    private int number;

    public synchronized void add() {
        while (number > 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number++;
        System.out.println(number);
        notify();
    }

    public synchronized void sub() {
        while (number == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number--;
        System.out.println(number);
        notify();
    }
}